import { ShelfStudyPlan } from '@/api/Shelf';
import { CityPicker } from '@/components/CityPicker';
import { tradeGroupResult } from '@/components/Trade/utils';
import { TradeCascaderSelect } from '@/components/TradeCascaderSelect';
import { useReactive } from 'ahooks';
import { App, Button, Cascader, Descriptions, Drawer, Modal } from 'antd';
import { useRef, useState } from 'react';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { ShelfUpperRef } from '../../../UpperContent';
import { StudyPlanDetail, StudyPlanDetailPorps } from '../../Detail';
type RecordType = ShelfStudyPlan;
type RecordObj = {
  area: string;
  entTypeCodeText: string;
  showTrade?: tradeGroupResult[];
  // [key: string]: string | number;
};
interface ListPorps {
  // 新增编辑事件
  onAddEdit?(value: any): void;
  // 打开弹窗事件
  onDetail?(): Promise<boolean>;
  // 删除事件
  onDelete?(): Promise<boolean>;
}

export function List({ onAddEdit }: ListPorps) {
  const [columns] = useState<YmColumnsType<RecordType>>([
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '组织类型',
      dataIndex: 'entTypeCodeText',
      key: 'entTypeCodeText',
      width: 100,
    },
    {
      title: '区域',
      dataIndex: 'regionName',
      key: 'regionName',
      ellipsis: true,
      width: 250,
    },
    {
      title: '行业',
      dataIndex: 'tradeName',
      ellipsis: true,
      key: 'tradeName',
      width: 250,
    },
    {
      key: '_operate',
      title: '操作',
      width: 140,
    },
  ]);
  const [tableDep, _reFreshTable] = useState<number>();
  const reFreshTable = () => _reFreshTable(Math.random());

  const upperRef = useRef<ShelfUpperRef>(null);
  const upperExtram = useReactive<{ guid?: string }>({ guid: undefined });
  const planRecord = useReactive<RecordObj>({
    area: '',
    entTypeCodeText: '',
  });
  // const [planRecord, setPlanRecord] = useState<ShelfStudyPlan>();
  const { modal } = App.useApp();
  const detailsPorps = useReactive<{ props?: StudyPlanDetailPorps }>({});
  return (
    <div className="safe_boss_page">
      <YmTable
        searchForm={{
          formItems: [
            {
              label: '名称',
              name: 'planName',
              valueType: {
                type: 'input',
              },
            },
            {
              label: '组织类型',
              name: 'entTypeCode',
              valueType: {
                type: 'select',
                selectProps: {
                  allowClear: true,
                  placeholder: '全部',
                  options: [
                    {
                      value: 'government',
                      label: '政府',
                    },
                    {
                      value: 'association',
                      label: '协会',
                    },
                    {
                      value: 'qiye',
                      label: '企业',
                    },
                  ],
                },
              },
            },
            {
              label: '行业',
              name: 'trade',
              // children: <TradeSelect allowClear placeholder="全部" />,
              children: <TradeCascaderSelect placeholder="全部" />,
            },
            {
              label: '区域',
              name: 'region',
              children: (
                <CityPicker
                  showCheckedStrategy={Cascader.SHOW_CHILD}
                  multiple
                  allowClear
                  placeholder="全部"
                  maxTagCount={1}
                />
              ),
            },
          ],
          span: 6,
        }}
        toolBar={{
          prefixNode: (
            <Button
              type="primary"
              onClick={() => {
                onAddEdit?.({});
              }}
            >
              新增
            </Button>
          ),
        }}
        columns={columns}
        request={async ({ page }, form = {}) => {
          const { region, ...params } = form;
          const { current = 0, pageSize = 10 } = page ?? {};
          const data = await ShelfStudyPlan.unShelfList(current, pageSize, {
            ...params,
            region: region
              ?.map((v: string[]) => {
                return v[v.length - 1];
              })
              .join(','),
          });
          return data;
        }}
        requestOptions={{
          reFreshDep: [tableDep],
          defaultPageSize: 20,
        }}
        rowKey="planId"
        operate={[
          {
            text: '编辑',
            key: 'edit',
            onClick(record) {
              onAddEdit?.({
                planId: record.guid,
                planName: record.name,
                faceImg: record.cover,
                cycleType: record.cycleType,
                cycleDay: record.cycleDay,
                learnObj: record.learnObj,
                learnMode: record.learnMode,
                isCharge: record.isCharge,
                // ...record.origin,
                region: record.origin.region,
                regionName: record.origin.regionName,
                entTypeCode: record.origin.entTypeCode,
                trade: record.origin.trade,
                tradeName: record.origin.tradeName,
                showTrade: record.origin.showTrade,
              });
            },
          },
          {
            text: '详情',
            key: 'detail',
            onClick(record) {
              console.log('嗲及先去', record);
              detailsPorps.props = {
                guid: record.guid,
                name: record.name,
                createTime: record.createTime,
                shelfInfo: {
                  area: record.area,
                  org: record.entTypeCodeText,
                  showTrade: record.showTradeArry,
                },
              };
            },
          },
          {
            text: '删除',
            key: 'delete',
            onClick(record) {
              modal.confirm({
                title: '提示',
                content: `确定要删除【${record.name}】吗`,
                async onOk() {
                  await ShelfStudyPlan.delete(record.guid);
                  reFreshTable();
                },
              });
            },
          },
          {
            text: '上架',
            key: 'listing',
            onClick(record) {
              // setPlanRecord(record);
              planRecord.area = record.area || '';
              planRecord.entTypeCodeText = record.entTypeCodeText || '';
              planRecord.showTrade = record.showTradeArry;
              upperExtram.guid = record.guid;
            },
          },
        ]}
      ></YmTable>
      <Modal
        width={480}
        title="上架"
        open={Boolean(upperExtram.guid)}
        onCancel={() => {
          upperExtram.guid = undefined;
          planRecord.area = '';
          planRecord.entTypeCodeText = '';
          planRecord.showTrade = undefined;
        }}
        centered
        destroyOnClose
        maskClosable={false}
        onOk={async () => {
          // const result = await upperRef.current?.submit();
          await ShelfStudyPlan.shelf.upper({ ...upperExtram });
          upperExtram.guid = undefined;
          planRecord.area = '';
          planRecord.entTypeCodeText = '';
          planRecord.showTrade = undefined;
          reFreshTable();
        }}
      >
        {/* <ShelfUpperModalContent ref={upperRef} useFor="learn" /> */}
        <Descriptions column={1}>
          <Descriptions.Item label="城市地域">{planRecord?.area}</Descriptions.Item>
          <Descriptions.Item label="组织类型">{planRecord?.entTypeCodeText}</Descriptions.Item>
          <Descriptions.Item label="所属行业">
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {planRecord?.showTrade &&
                planRecord?.showTrade.map((t) => {
                  return (
                    <div key={t.entTypeCode} style={{ marginBottom: '6px' }}>
                      {t.name}——{t.tradeDictString};
                    </div>
                  );
                })}
            </div>
          </Descriptions.Item>
        </Descriptions>
      </Modal>
      <Drawer
        width={800}
        open={Boolean(detailsPorps.props)}
        title="详情"
        onClose={() => {
          detailsPorps.props = undefined;
        }}
      >
        <StudyPlanDetail {...detailsPorps.props} />
      </Drawer>
    </div>
  );
}
